package com.acc.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.acc.entity.Admin;
import com.acc.entity.Role;
import com.acc.entity.User;
import com.acc.service.AdminLoginService;
import com.acc.service.AdminService;
import com.acc.service.impl.AdminLoginServiecImpl;
import com.acc.service.impl.AdminServiceImpl;
import com.acc.utils.Md5Utils;

/**
 * @author 朱春阳
 */
public class AdminLoginRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminLoginRegister() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取表单里的数据
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("password");
		String password = null;
		if(pwd != null) {
			password = Md5Utils.md5(pwd);
			System.out.println(password);
		}
		AdminLoginService adminService = new AdminLoginServiecImpl();
		Admin admin = adminService.isLogin(userName, password);
		
		//根据用户名查询用户的角色和对应的uri地址
		
		HttpSession httpSession = request.getSession();
		if(admin != null) {
			//查询出所有的角色
			List<String> roles = adminService.getAllRolesByAdminName(userName);
			Set<String> set = null;
			Map<String, Set<String>> map = new HashMap<>();
			for (String role : roles) {
				set = adminService.getAllURIbyRole(role);
				map.put(role, set);
			}
			Role authority = new Role();
			authority.setRelation(map);
			httpSession.setAttribute("role", authority);
			httpSession.setAttribute("admin", admin);
			response.sendRedirect("/TicketManager/main.jsp");
//			request.getRequestDispatcher("/main.jsp").forward(request, response);
		}else {
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		
	}

}
